package com.tigercel.xiangchengyun.ui.fragments

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.adapter.NewsAdapter
import com.tigercel.xiangchengyun.adapter.NewsBannerAdapter
import com.tigercel.xiangchengyun.entity.Banner
import com.tigercel.xiangchengyun.entity.NewsBean
import com.tigercel.xiangchengyun.ui.activities.WebViewActivity
import com.tigercel.xiangchengyun.ui.custom.lbanners.LMBanners
import com.tigercel.xiangchengyun.ui.custom.lbanners.transformer.TransitionEffect
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.fragment_news_normal.*
import org.jetbrains.anko.support.v4.toast
import java.text.SimpleDateFormat

class NewsCommonFragment : Fragment() {
    companion object {

        fun newInstance(channelPosition: Int): NewsCommonFragment? {
            val fragment = NewsCommonFragment()
            val bundle = Bundle()
            bundle.putInt("channelPosition", channelPosition)
            fragment.arguments = bundle
            return fragment

        }

    }

    private var containerView: View? = null
    private var banner: LMBanners<Any>? = null
    private var headBanner: View? = null
    private var channelPosition: Int = 0
    private val ACTION_REFRESH = 1
    private val ACTION_LOAD_MORE = 2
    private var mCurrentAction = ACTION_REFRESH
    private var mCurrentPageIndex = 1
    private var localDatas: PreferencesUtil? = null
    private lateinit var newsAdapter: NewsAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        containerView = inflater.inflate(R.layout.fragment_news_normal, container, false)
        if (arguments != null)
            channelPosition = arguments!!.getInt("channelPosition")
//        Log.e("id编号3", channelPosition.toString())
        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerview.layoutManager = LinearLayoutManager(activity)
        newsAdapter = NewsAdapter(ArrayList()) {
            val intent = Intent()
            intent.putExtra("title", it.title)
            intent.putExtra("url", it.url)
            intent.putExtra("id", it.content_id)
            intent.putExtra("model", it.model_name)
            intent.setClass(activity, WebViewActivity::class.java)
            startActivity(intent)
        }
        recyclerview.adapter = newsAdapter
        headBanner = View.inflate(activity, R.layout.banners, null)
        banner = headBanner?.findViewById(R.id.banners)
        banner!!.setIndicatorBottomPadding(8)
        banner!!.setHoriZontalTransitionEffect(TransitionEffect.Default)
        recyclerview.refresh()
        localDatas = PreferencesUtil(activity)
        getContent("create")
    }

    private fun switchActionAndLoadData(action: Int) {
        mCurrentAction = action
        when (mCurrentAction) {
            ACTION_REFRESH -> {
                newsAdapter.clear()
                mCurrentPageIndex = 1
            }
            ACTION_LOAD_MORE -> mCurrentPageIndex++
        }

    }

//    private fun loadbanners() {
//        var bannerBean = Banner(0, "", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1522765537318&di=d6ffbf06f8204eb28510cbc8784918c7&imgtype=0&src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2Ffbfc3e13a06f6581629970417c0d8ec5286ddfeb.jpg", "")
//        var bannerBean2 = Banner(0, "", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1522765809166&di=17b19b778ab60b9d3b214b5c3a256ea0&imgtype=0&src=http%3A%2F%2Fp3.ifengimg.com%2Fa%2F2017_29%2F4f0ea37d91daa59_size103_w1600_h1000.jpg", "")
//        var bannerBean3 = Banner(0, "", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523360415&di=b483f5dab40ad6c0450110601af6dbde&imgtype=jpg&er=1&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farchive%2F64222c045288c88d83cebb57ee71c5bb25780742.jpg", "")
//        var banners: MutableList<Banner>
//        banners = ArrayList()
//        banners.add(bannerBean)
//        banners.add(bannerBean2)
//        banners.add(bannerBean3)
//        banner!!.setAdapter(NewsBannerAdapter(activity), listOf(bannerBean, bannerBean2, bannerBean3))
//    }
//    private fun loadNews() {
//        var news1 = NewsBean("", 1, "习近平:吹响建设科技强国号角国号角国号角", "新华网", "www.baidu.com", "6小时前", 0, listOf(), 100)
//        var news2 = NewsBean("", 1, "李志强到我市调研工作", "央视新闻", "www.google.com", "7小时前", 0, listOf(), 200)
//        var news3 = NewsBean("", 1, "改善人民居住环境", "大和网", "www.9527.com", "8小时前", 0, listOf(), 10)
//        var news4 = NewsBean("", 1, "扶贫车间搭建就业脱贫", "人民日报", "www.hahah.com", "9小时前", 0, listOf(), 88)
//        var news5 = NewsBean("", 1, "非法集资案高发", "项城云", "www.eeeeeee.com", "10小时前", 0, listOf(), 999)
//        var news6 = NewsBean("", 1, "非法集资案高发", "项城云", "www.eeeeeee.com", "10小时前", 0, listOf(), 999)
//        var news7 = NewsBean("", 1, "非法集资案高发", "项城云", "www.eeeeeee.com", "10小时前", 0, listOf(), 999)
//        var news8 = NewsBean("", 1, "非法集资案高发", "项城云", "www.eeeeeee.com", "10小时前", 0, listOf(), 999)
//        var news9 = NewsBean("", 1, "非法集资案高发", "项城云", "www.eeeeeee.com", "10小时前", 0, listOf(), 999)
//        var news: MutableList<NewsBean>
//        news = ArrayList()
//        news.add(news1)
//        news.add(news2)
//        news.add(news3)
//        news.add(news4)
//        news.add(news5)
//        news.add(news6)
//        news.add(news7)
//        news.add(news8)
//        news.add(news9)
//        newsAdapter.addAll(news)
//        recyclerview.refreshComplete()
//    }

    override fun onDestroy() {
        super.onDestroy()
        banner!!.clearImageTimerTask()
    }

    private fun getContent(type: String) {

        val devicesId = Settings.System.getString(activity!!.getContentResolver(), Settings.System.ANDROID_ID)
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        OkGo.get<String>(Global.baseUrl + "v1/channel/content")
                .tag(this)
                .params("channel_id", channelPosition)
                .params("device_code", devicesId)
                .params("user_id", localDatas!!.preferences["user_id"])
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val content = response!!.body()
                        val status = JsonUtil.get_key_string("status", content!!)
                        val msg = JsonUtil.get_key_string("msg", content!!)
                        val code = JsonUtil.get_key_string("code", content!!)
                        val data = JsonUtil.get_key_string("data", content!!)
                        if (status == "0") {
                            var banners1: MutableList<Banner>
                            banners1 = ArrayList()
                            banners1.clear()
                            val banners = JsonUtil.getList("banner", data)
                            if (banners.isNotEmpty()) {
                                if (type == "create") {
                                    recyclerview.addHeaderView(headBanner)
                                }
                                for (i in 0 until banners.size) {
                                    var img = JsonUtil.get_key_string("img", banners[i])
                                    var url = JsonUtil.get_key_string("url", banners[i])
                                    var name = JsonUtil.get_key_string("title", banners[i])
                                    var bannerBean = Banner(i, name, img, url)
                                    banners1.add(bannerBean)
                                }
                                banner!!.setAdapter(NewsBannerAdapter(activity), banners1 as List<Any>?)
                            }
                            var details = JsonUtil.getList("content", data)

                            var news: MutableList<NewsBean>
                            news = ArrayList()
                            for (i in 0 until details.size) {
                                var content_id = JsonUtil.get_key_string("content_id", details[i])
                                var title = JsonUtil.get_key_string("title", details[i])
                                var author = JsonUtil.get_key_string("author", details[i])
                                var thumb_img = JsonUtil.get_key_string("thumb_img", details[i])
                                var url = JsonUtil.get_key_string("url", details[i])
                                var model_name = JsonUtil.get_key_string("model_name", details[i])
                                var readcount = JsonUtil.get_key_string("readcount", details[i])
                                var pub_time = JsonUtil.get_key_string("pub_time", details[i]).toLong()
                                val d = sdf.format(pub_time * 1000L)
                                var news1 = NewsBean(content_id, 1, title, author, url, d, 0, thumb_img, readcount.toInt(), model_name)
                                news.add(news1)
                            }
                            newsAdapter.addAll(news)
                            if (activity != null) {
                                recyclerview.refreshComplete()
                            }

                            recyclerview.setLoadingListener(object : XRecyclerView.LoadingListener {
                                override fun onRefresh() {
                                    getContent("refresh")
                                }

                                override fun onLoadMore() {
                                    getMore()
                                }
                            })
                        } else {
                            toast(getString(R.string.readFaile))
                        }
                    }

                })
    }

    private fun getMore() {

        val sdf = SimpleDateFormat("yyyy-MM-dd")
        OkGo.get<String>(Global.baseUrl + "v1/channel/content/page")
                .tag(this)
                .params("channel_id", channelPosition)
                .params("device_code", Global.getDeviceId())
                .params("page_size", "10")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val content = response!!.body()
                        val status = JsonUtil.get_key_string("status", content!!)
                        val msg = JsonUtil.get_key_string("msg", content!!)
                        val code = JsonUtil.get_key_string("code", content!!)
                        val data = JsonUtil.getList("data", content!!)
                        if (status == "0") {
                            var news: MutableList<NewsBean>
                            news = ArrayList()
                            if (data.isNotEmpty()) {
                                for (i in 0 until data.size) {
                                    var content_id = JsonUtil.get_key_string("content_id", data[i])
                                    var title = JsonUtil.get_key_string("title", data[i])
                                    var author = JsonUtil.get_key_string("author", data[i])
                                    var thumb_img = JsonUtil.get_key_string("thumb_img", data[i])
                                    var url = JsonUtil.get_key_string("url", data[i])
                                    var readcount = JsonUtil.get_key_string("readcount", data[i])
                                    var model_name = JsonUtil.get_key_string("model_name", data[i])
                                    var pub_time = JsonUtil.get_key_string("pub_time", data[i]).toLong()
                                    val d = sdf.format(pub_time * 1000L)
                                    var news1 = NewsBean(content_id, 1, title, author, url, d, 0, thumb_img, readcount.toInt(), model_name)
                                    news.add(news1)
                                }
                                newsAdapter.addAll(news)
                                recyclerview.loadMoreComplete()
                            } else {
                                toast(getString(R.string.alreadyloadall))
                            }
                        } else {
                            toast(getString(R.string.readFaile))
                        }
                    }
                })
    }

    override fun onResume() {
        super.onResume()
//        getContent("create")
    }
}
